//
//  HistoryViewModel.swift
//  Chatup
//
//  Created by op on 2023/10/20.
//

import Foundation
import FirebaseAnalytics

extension Int64 {
    func convertMillisecondsToDateString() -> String {
        let date = Date(timeIntervalSince1970: TimeInterval(self) / 1000)
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy.MM.dd HH:mm:ss"
        
        return dateFormatter.string(from: date)
    }
}

struct HistoryModel:Identifiable{
    let id = UUID()
    var iconString:String
    var msg:String
    var time:String
    var roleId:Int
    var name:String
    
    init(name:String, iconString: String, msg: String, time: String, roleId: Int) {
        self.iconString = iconString
        self.msg = msg
        self.time = time
        self.roleId = roleId
        self.name = name
    }
}

@MainActor
class HistoryViewModel:ObservableObject{
    @Published var items:[HistoryModel] = []
    @Published var showSetting = false
    @Published var showVip = false
    var logfrom = ""
    var needSaveMessage:[MsgModel] = []
    init(){
        logShowHistory()
//        items.append(.init(iconString: "icon_jean", msg: "hi", time: "2011.09.20  23:21:00"))
//        items.append(.init(iconString: "icon_jean", msg: "Give me a step-by-step plan to ...", time: "2011.09.20  23:21:00"))
//        items.append(.init(iconString: "icon_jean", msg: "how are you today", time: "2011.09.20  23:21:00"))

    }
    
    
    func refreshUI(category:String) {
        getData(category: category)
        showVip = !UserDefaults.standard.bool(forKey: "kWhetherVip")
    }
    
    func getData(category:String){
        items.removeAll()
        needSaveMessage.removeAll()
        let models = RoleDataManager.share.getRoles(category: category)
        models.forEach { model in
            let msgModels = MassageDataManager.share.getMsg(roleId: model.serverId)
            let textMsgModels = msgModels.filter({ $0.isText() && $0.messageType == .text })
            if textMsgModels.count > 0{
                if let msgModel = textMsgModels.last {
                    items.append(.init(name:model.name ,iconString: model.icon, msg: msgModel.message, time: msgModel.createTime?.convertMillisecondsToDateString() ?? "",roleId: model.serverId))
                    if self.needAddImageMessage(role: model, msgs: msgModels){
                        let imgMsg = MsgModel(type: .bot, messageType: .image,message: model.images.first!, roleId: model.serverId, isLike: false, isUnlike: false)
                        needSaveMessage.append(imgMsg)
                    }
                }
               
               
            }else{
                let msgModel = MsgModel(type: .bot, messageType: .text,message: model.i18nGreeting(), roleId: model.serverId, isLike: false, isUnlike: false)
             
                needSaveMessage.append(msgModel)
                if self.needAddImageMessage(role: model, msgs: msgModels){
                    let imgMsg = MsgModel(type: .bot, messageType: .image,message: model.images.first!, roleId: model.serverId, isLike: false, isUnlike: false)
                    needSaveMessage.append(imgMsg)
                }
                items.append(.init(name:model.name ,iconString: model.icon, msg: model.i18nGreeting(), time: Int64(Date().timeIntervalSince1970 * 1000).convertMillisecondsToDateString(),roleId: model.serverId))
           
            }
        }
        self.saveMessage(msgs: needSaveMessage)
    }
    
    private func needAddImageMessage(role:RoleModel,msgs:[MsgModel])-> Bool{
        if role.images.isEmpty {return false}
        if msgs.isEmpty {return true}
        if msgs.last!.message == role.greeting && msgs.last!.isText(){
            return true
        }
        return false
    }
    
    private func saveMessage(msgs:[MsgModel]) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            MassageDataManager.share.saveMsgs(msgs: msgs)
        }
    }

}

extension HistoryViewModel {
    func logShowHistory() {
        Analytics.logEvent("characters_page_show", parameters: nil)

    }
    func logHistoryClick(roleId:String) {
        Analytics.logEvent("characters_page_click", parameters: ["role_id":roleId])

    }
    func logFreeClick() {
        Analytics.logEvent("characters_page_free_click", parameters: nil)

    }
    
    
}
